//
//  ContentView.swift
//  TomatoClock
//
//  Created by DaleGuo on 2023/10/30.
//

import ActivityKit
// https://github.com/tfmart/LottieUI
import LottieUI
import SwiftUI
import SwiftUICharts
import WidgetKit

struct ContentView: View {
//    @State private var acticity: Activity<CountDonwAttributes>? = nil
    
    @AppStorage("is_starting", store: UserDefaults(suiteName: "group.com.dale.tomato_clock")) var is_starting = false
    
    @AppStorage("tomatoDate", store: UserDefaults(suiteName: "group.com.dale.tomato_clock")) var tomatoDate: Date = Date().addingTimeInterval(25*60)
    
    @AppStorage("sliderValue", store: UserDefaults(suiteName: "group.com.dale.tomato_clock")) var sliderValue: Double = 25
    @AppStorage("countOfFinished", store: UserDefaults(suiteName: "group.com.dale.tomato_clock")) var countOfFinished: Int = 0
 
    @State var countValue: Double = 1
    
    @State var isFinished = false
    
    @EnvironmentObject var vm: HomeViewModel
    
    var notificationHelper = NotificationHandler.Notification
    
    let timer = Timer.publish(every: 1.0, on: .main, in: .common).autoconnect()
    
    var body: some View {
        ZStack {
            Color.gray.opacity(0.1)
                .ignoresSafeArea(.all)
            
            LottieView("success_animation")
                .play(isFinished)
                .speed(1.0)
                .opacity(isFinished ? 1 : 0)
                .zIndex(100)

            NavigationStack {
                VStack {
                    ZStack {
                        LottieView("working")
                            .play(is_starting)
                            .loopMode(.loop)
                            .opacity(is_starting ? 1 : 0)
                            
                        LottieView("resting")
                            .play(!is_starting)
                            .loopMode(.loop)
                            .opacity(!is_starting ? 1 : 0)
                    }
                        
                    if is_starting {
                        Text(tomatoDate, style: .timer)
                            .modifier(TimeModifier())
                            .onReceive(timer, perform: { now in
                                // 每秒刷新判断，
                                if now > tomatoDate.addingTimeInterval(1) {
                                    // 如果现在超过了tomatoDate
                                    is_starting = false
                                    isFinished = true
                                        
                                    HapticManager.instance.finish_tomato_clock()
                                        
                                    WidgetCenter.shared.reloadTimelines(ofKind: "TomatoClockWidget")
                                        
                                    tomatoDate = Date().addingTimeInterval(60*sliderValue + 1)
                                        
                                    // 完成后的效果展示,根据动画实际调整
                                    DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
                                        isFinished = false
                                    }
                                        
                                    // 这也可以测试 is_starting = false 时，会不会持续订阅timer，答案：不会！很好
                                    vm.addItem(clock_time: Int(sliderValue))
                                }
                            })
                            .frame(height: 300)
                    } else {
                        VStack {
                            HStack {
                                Text(Int(sliderValue).description)
                                    .modifier(TimeModifier())
                                Text("mins")
                                    .offset(y: 20)
                                    .italic()
                                    .bold()
                            }.padding(0)
                                
                            Slider(value: $sliderValue, in: 1 ... 100, step: 5.0)
                                .onChange(of: sliderValue, initial: true) { _, _ in
                                        
                                    HapticManager.instance.impact(style: .light)
                                        
                                    tomatoDate = Date().addingTimeInterval(10*sliderValue + 1)
                                    countValue = sliderValue
                                    WidgetCenter.shared.reloadTimelines(ofKind: "TomatoClockWidget")
                                }
                                .padding(.horizontal)
                        }
                        .frame(height: 300)
                    }
                        
                    Button {
                        toggleButton()
                    } label: {
                        Text(is_starting ? "Cancle" : "Start")
                            .font(.title)
                            .padding()
                            .bold()
                            .foregroundStyle(Color.white)
                            .background(is_starting ? Color.gray.opacity(0.4) : Color.accentColor)
                            .clipShape(RoundedRectangle(cornerRadius: 25))
                    }
                }
                .toolbar(content: {
                    if !is_starting {
                        ToolbarItem(placement: .topBarLeading) {
                            NavigationLink {
                                SettingViews()
                            } label: {
                                Image(systemName: "ellipsis")
                            }
                        }
                    }
                        
                    ToolbarItem(placement: .topBarTrailing) {
                        HStack(spacing: 3) {
                            NavigationLink {
                                TableView()
                                    
                            } label: {
                                Text("\(countOfFinished) x")
                                    .bold()
                                    .foregroundStyle(Color.accentColor)
                                    
                                LottieView("tomato_jump")
                                    .play(isFinished)
                                    .frame(width: 20, height: 20)
                            }
                        }
                    }
                                       
                })
            }
        }
    }
    
    
    
    private func toggleButton() {
        HapticManager.instance.impact(style: .medium)

        is_starting.toggle()
        tomatoDate = Date().addingTimeInterval(10*sliderValue + 1)
        
//        ToggleButtonIntent().donate()
        
        // 刷新widget
        WidgetCenter.shared.reloadTimelines(ofKind: "TomatoClockWidget")
        
        // 设置通知
        if is_starting {
            notificationHelper.sendTomatoNotification(tomatoDate: tomatoDate)
            ActivityWidgetUtil.startActivity(tomatoDate: tomatoDate)
        } else {
            notificationHelper.cancelNotification()
            ActivityWidgetUtil.stopActivity()
        }
    }
}

struct TimeModifier: ViewModifier {
    func body(content: Content) -> some View {
        content
            .font(.system(size: 100))
            .italic()
            .fontWeight(.heavy)
    }
}
    
#Preview {
    ContentView()
        .environmentObject(HomeViewModel())
}
